package com.lagou.filter;


import com.lagou.entity.Result;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SignInFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
//          无效
//        if (request.getMethod().equalsIgnoreCase("post"))
//            request.setCharacterEncoding("utf-8");
//        response.setContentType("text/html;charset=utf-8");

        String url = request.getRequestURI().toLowerCase();
        System.out.println(url);
        //  只处理点击<添加>按钮的访问
        if (url.contains("add.check")) {
            Object sessionId = request.getSession().getAttribute("SessionId");
            System.out.println("过滤器拦截,登录状态 = " + (sessionId != null));
            if (sessionId != null)
                response.getWriter().print(Result.toJsonString(1, "addStudent.html", ""));
            else {
                request.getSession().setAttribute("SessionId", null);
                response.getWriter().print(Result.toJsonString(-1, "passport.html", "请先登录"));
            }
        } else
            //放行
            filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }


}
